package persistence;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class GenericDao<E> {
	
	Session session;
	Transaction transaction;
	
	E entity;

	
	public GenericDao(E entity) {
		this.entity = entity;
	}
	
	public void create(E e) throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
				session.save(e);
			transaction.commit();
		session.close();
	}
	
	public void update(E e) throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
				session.update(e);
			transaction.commit();
		session.close();
	}
	
	public void delete(E e) throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
				session.delete(e);
			transaction.commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<E> findAll(){
		session = HibernateUtil.getSessionFactory().openSession();
			List<E> lista = session.createCriteria(entity.getClass()).list();
			session.close();
		return lista;
	}
	
	@SuppressWarnings("unchecked")
	public E findByCode(Integer cod){
		session = HibernateUtil.getSessionFactory().openSession();
			E ent = (E)session.get(entity.getClass(), cod);
			session.close();
		return ent;
	}
	
	


}
